package 并发包;

/**
 * ThreadLocal为变量在每个线程中都创建了一个副本, 那么每个线程可以操作自己内部的副本变量, 互不影响
 * Created by huangyu on 2018/9/1 10:00
 */
class Count {
	public Integer count = 0;

	public static final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
		@Override
		protected Integer initialValue() {
			return 0;
		}
	};

	public Integer getCount() {
		count = threadLocal.get() + 1;
		threadLocal.set(count);
		return count;
	}
}

class ThreadClass extends Thread {
	private Count count;

	public ThreadClass(Count count) {
		this.count = count;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			System.out.println(getName() + "--" + count.getCount());
		}
	}
}

public class ThreadLocalDemo {
	public static void main(String[] args) {
		Count count = new Count();
		ThreadClass t1 = new ThreadClass(count);
		ThreadClass t2 = new ThreadClass(count);
		ThreadClass t3 = new ThreadClass(count);
		t1.start();
		t2.start();
		t3.start();
	}

}
